from datetime import datetime,timedelta

from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

from pom.basePage import BasePage


class Article(BasePage):
    title_input = (By.NAME, 'article.title')
    iframe = (By.XPATH, '//*[@id="cke_1_contents"]/iframe')
    content_input = (By.XPATH, '/html/body/p')
    summary_input = (By.NAME,"article.summary")
    meta_keywords_input = (By.NAME,"article.meta_keywords")
    meta_description_input = (By.NAME, "article.meta_description")
    order_number_input = (By.NAME, "article.order_number")
    link_to_input = (By.NAME, "article.link_to")
    created_input = (By.NAME, "article.created")
    comment_status_input = (By.XPATH,'//*[@id="form"]/div/div[1]/div/div[3]/div/div/div[2]/div/div[7]/div/span/small')
    btn = (By.XPATH,'//*[@id="form"]/div/div[2]/div[1]/div/button[1]')
    comment_status =(By.ID, 'comment_status')

    form =['title','content','summary','meta_keywords','meta_description','order_number','link_to','created','comment_status']
    toast = (By.CLASS_NAME, 'toast-title')
    toast_message = (By.CLASS_NAME, 'toast-message')

    def __init__(self,driver,hostname):
        super().__init__(driver)
        self.base_url = f"http://{hostname}/jpress/admin/index".format(hostname=hostname)
        self.url = f"http://{hostname}/jpress/admin/article/write".format(hostname=hostname)
    def goto_article_page(self):
        self.goto_page(self.url)

    def fill_input(self, element_name, text):
        self.input_text(self.__getattribute__(element_name), text)

    def comment_status_checked(self):
        return True if self.find_element(self.comment_status).get_property('value') == 'true' else False
    def click_comment_status(self):
        self.click(self.comment_status_input)
    def set_comment_status(self,status=False):
        if not (status and self.comment_status_checked()):
            self.click_comment_status()

    def fill_form(self,form_info:dict):
        '''
        fill the whole form
        :param form_info: dict of form_info to fill in
        :return: None
        '''
        for element in self.form:
            if element=='content':
                self.switch_to_iframe(self.iframe)
                self.fill_input(f'{element}_input'.format(element), form_info.get(element,''))
                self.switch_to_default()
            elif element == 'comment_status':
                status_to_set = form_info.get('comment_status',True)
                self.set_comment_status(status_to_set)
            else:
                self.fill_input(f'{element}_input'.format(element), form_info.get(element,''))
    def submit(self):
        self.click(self.btn)

    def wait_until_toast_present(self):
        self.wait_until_element_present(self.toast_message)
    def get_toast_text(self):
        return self.get_text(self.toast_message)

    def get_form_data(self):
        self.form_data ={}
        for k in self.form:
            element = self.__getattribute__(f'{k}_input'.format(k))
            if k == "comment_status":
                self.form_data[k]= self.comment_status_checked()
            elif k=='content':
                self.switch_to_iframe(self.iframe)
                self.wait(1)
                self.form_data[k]=self.get_text(self.content_input)
                self.switch_to_default()
            else:
                if k in ['title','order_number','link_to','created']:
                    self.form_data[k] = self.get_value(element)
                else:
                    self.form_data[k]=self.get_text(element)
        return self.form_data

    def assert_time(self,atime,btime):
        atime = datetime.strptime(atime,"%Y-%m-%d %H:%M:%S")
        btime = datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
        time_delta = timedelta(seconds=3)
        if btime-atime <= time_delta:
            return True
        return False

    def assert_form_data(self,expected):
        fd = self.get_form_data()
        print(expected)
        print(fd)
        for k,exp in expected.items():
            print("a,b:%s,%s" % (fd[k],exp))
            if k =='order_number':
                assert int(fd[k]) == exp
            elif k == 'created':
                self.assert_time(exp,fd[k])
            else:
                print(fd[k],exp)
                assert fd[k] == exp

